package org.example.memora.service.serviceImpl;

import org.example.memora.common.result.Result;
import org.example.memora.entity.UserFollow;
import org.example.memora.mapper.UserFollowMapper;
import org.example.memora.mapper.UserMapper;
import org.example.memora.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public Result<?> follow(Long followerId, Long followedId) {
        // 构造关注记录
        UserFollow record = new UserFollow();
        record.setFollowerId(followerId);
        record.setFollowedId(followedId);
        record.setCreatedAt(Instant.now());
        if(userMapper.findById(record.getId())==null){
            return Result.error("关注的用户不存在");
        }
        int count = userFollowMapper.insert(record);
        if (count > 0) {
            return Result.success(1, "关注成功");
        }
        return Result.error("关注失败");
    }

    @Transactional
    @Override
    public Result<?> unfollow(Long followerId, Long followedId) {
        // 构造参数 Map
        Map<String, Object> params = new HashMap<>();
        params.put("followerId", followerId);
        params.put("followedId", followedId);
        if(userMapper.findById(followedId)==null){
            return Result.error("要取关的用户不存在");
        }
        int count = userFollowMapper.deleteByFollowerAndFollowed(params);
        if (count > 0) {
            return Result.success(1, "取消关注成功");
        }
        return Result.error("取消关注失败");
    }

    @Override
    public Result<?> listFollowings(Long followerId, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        Map<String, Object> params = new HashMap<>();
        params.put("followerId", followerId);
        params.put("limit", pageSize);
        params.put("offset", offset);
        List<UserFollow> list = userFollowMapper.selectByFollowerId(params);
        int total = userFollowMapper.countByFollowerId(followerId);
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        return Result.success(result);
    }
}
